package transcoding

import play.api.Logger
import java.io.InputStream

class TranscodedInputStream(adapteeInputStream: InputStream, listener: InputStreamListener) extends InputStream {

  override def read = {
    val read = adapteeInputStream.read
    listener.onRead

    read
  }

  override def read(b: Array[Byte]) = {
    val read = adapteeInputStream.read(b)
    listener.onRead(b)
    
    read
  }

  override def read(b: Array[Byte], s: Int, off: Int) = {
    val read = adapteeInputStream.read(b, s, off)
    listener.onRead(b, s, off)

    read
  }

  override def close = {
    Logger.debug("Closing transcode stream...")
    listener.onCloseRequest(adapteeInputStream)
  }

  override def markSupported = {
    adapteeInputStream.markSupported
  }

  override def reset = {
    adapteeInputStream.reset
  }

  override def available = {
    adapteeInputStream.available
  }

  override def mark(readLimit: Int) = {
    adapteeInputStream.mark(readLimit)
  }

  override def skip(n: Long) = {
    adapteeInputStream.skip(n)
  }
}

trait InputStreamListener {
  def onRead {}
  def onRead(b: Array[Byte]) {}
  def onRead(b: Array[Byte], s: Int, off: Int) {}
  def onSkip {}
  // The TranscodedInputStream never closes its adaptee
  // but it will delegate to the listeners
  def onCloseRequest(adaptedInputStream: InputStream)
}
